package com.atwork.config.shiro;

import com.atwork.model.normal.SysUser;
import com.atwork.model.vo.ShiroUser;
import com.atwork.service.SysUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @CreateBy: zhaojun
 * @CreateTime: 2018-08-04
 * @Desc: ShiroRealm配置
 */

public class ShiroRealm extends AuthorizingRealm{
    @Autowired
    private SysUserService sysUserService;
    //认证.登录
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken utoken=(UsernamePasswordToken) token;//获取用户输入的token
        String username = utoken.getUsername();
        SysUser sysUser = sysUserService.getUserByLoginName(username);
        return new SimpleAuthenticationInfo(sysUser,sysUser.getPassword(),this.getClass().getName());//放入shiro.调用CredentialsMatcher检验密码
    }
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        ShiroUser user=(ShiroUser) principal.fromRealm(this.getClass().getName()).iterator().next();//获取session中的用户
        List<String> permissions=new ArrayList<>();
        Set<String> roleListNames = user.getRoleListNames();
        Set<String> resourceUrls = user.getResourceUrls();
        for(String roleName : roleListNames) {
            permissions.add(roleName);
        }
        for(String resourceUrl : resourceUrls) {
            permissions.add(resourceUrl);
        }
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.addStringPermissions(permissions);//将权限放入shiro中.
        return info;
    }

}
